import { useEffect, useState } from 'react';
import styles from './index.less';
import { Modal, Form, Input, Radio, Select, Button } from 'antd';
import moment from 'moment';
import _ from 'lodash';

import { TRMessage } from '#/components';
import TRNotification from '#/utils/notification';
import { HttpCode } from '#/utils/contacts';
import { useStaticState } from '#/utils/trHooks';
import { operateLogModal } from '@/assets';

import { saveOrUpdate } from '../../services.js';

const EditorModel = ({ data, code, onPress }) => {
  const [isAdd] = useState(code === 'add');
  const [showModal, setShowModal] = useState(true);
  const [changeData, setChangeData] = useState({});
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();
  const staticData = useStaticState({
    titleObj: {
      add: '新增',
      edit: '编辑',
    },
    formList: [
      {
        type: 'Input',
        required: true,
        message: '请输入11位手机号',
        label: '手机号',
        rules: [{ type: 'string', min: 11, max: 11, message: '请输入11位手机号' }],
        code: 'phoneNum',
        props: {
          disabled: !isAdd,
        },
      },
      {
        type: 'Input',
        message: '请输入不超过20个字符',
        label: '用途',
        rules: [{ type: 'string', max: 20, message: '请输入不超过20个字符' }],
        code: 'useTo',
      },
      {
        type: 'Input',
        message: '请输入不超过20个字符',
        label: '关键字',
        rules: [{ type: 'string', max: 20, message: '请输入不超过20个字符' }],
        code: 'keyword',
      },
      {
        type: 'Input',
        required: true,
        message: '请输入不超过20个字符',
        label: '实名认证',
        rules: [{ type: 'string', max: 20, message: '请输入不超过20个字符' }],
        code: 'realNameAuth',
      },
      {
        type: 'Input',
        message: '请输入不超过20个字符',
        label: '套餐',
        rules: [{ type: 'string', max: 20, message: '请输入不超过20个字符' }],
        code: 'thali',
      },
      {
        type: 'Input',
        message: '请输入不超过20个字符',
        label: '手机',
        rules: [{ type: 'string', max: 20, message: '请输入不超过20个字符' }],
        code: 'phoneName',
      },
      {
        type: 'Select',
        required: true,
        message: '请选择卡槽',
        label: '卡槽',
        code: 'slot',
        options: [
          { label: 1, value: 1 },
          { label: 2, value: 2 },
        ],
      },
      {
        type: 'Select',
        message: '请选择运营商',
        label: '运营商',
        code: 'operator',
        options: [
          { label: '电信', value: '电信' },
          { label: '移动', value: '移动' },
          { label: '联通', value: '联通' },
        ],
      },
      {
        type: 'Input',
        required: true,
        message: '请输入服务密码',
        label: '服务密码',
        rules: [{ type: 'string', min: 6, max: 6, message: '请输入6位服务密码' }],
        code: 'servicePassword',
      },
      {
        type: 'Radio',
        label: '状态',
        code: 'status',
      },
    ],
  });

  useEffect(() => {
    init();
  }, []);

  const init = () => {
    if (isAdd) {
      //新增默认勾选状态
      setChangeData({ status: true });
    }
    form.setFieldsValue(data);
  };

  const onFinish = async () => {
    try {
      await form.validateFields();
      if (_.isEmpty(changeData)) {
        _onCancel();
        return;
      }
      setConfirmLoading(true);
      const res = await saveOrUpdate({ id: data?.id, ...changeData });
      setConfirmLoading(false);
      if (res?.statusCode === HttpCode.SUCCESS) {
        TRMessage.success('保存成功');
        _handleOk();
      } else {
        TRMessage.error(res?.message || '保存失败');
      }
    } catch (errorInfo) {
      // console.log('校验失败:', errorInfo);
    }
  };

  const renderItem = ({ type, message, options, props }) => {
    switch (type) {
      case 'Input':
        return <Input placeholder={message} {...props} />;
      case 'Select':
        return <Select placeholder={message} options={options} {...props} />;
      case 'Radio':
        return (
          <Radio.Group {...props}>
            <Radio value={true}>启用</Radio>
            <Radio value={false}>停用</Radio>
          </Radio.Group>
        );
    }
  };

  // 取消按钮
  const _onCancel = () => {
    setShowModal(false);
    onPress({ index: 0 });
  };

  // 提交按钮
  const _handleOk = () => {
    setShowModal(false);
    onPress({ index: 1 });
  };

  const { formList, titleObj } = staticData;
  return (
    <Modal
      className={styles.submitStatusModal}
      centered={true}
      title={
        <div className={styles.modalTitle}>
          <img src={operateLogModal} />
          <span className={styles.text}>{titleObj[code]}</span>
        </div>
      }
      visible={showModal}
      onCancel={_onCancel}
      footer={[
        <Button key="back" onClick={_onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={confirmLoading} onClick={onFinish}>
          确定
        </Button>,
      ]}
    >
      <Form
        form={form}
        className={styles.form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        initialValues={{ status: true }}
        colon={false}
        labelAlign="left"
        autoComplete="off"
        requiredMark={false}
        onValuesChange={(e) => {
          setChangeData({ ...changeData, ...e });
        }}
      >
        {formList.map((t) => (
          <Form.Item
            key={t.code}
            label={t.label}
            name={t.code}
            rules={[{ required: t.required, message: t.message }].concat(t.rules || [])}
          >
            {renderItem(t)}
          </Form.Item>
        ))}
      </Form>
    </Modal>
  );
};

class MyModel {
  __key__ = '';

  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <EditorModel
            {...props}
            onPress={(result) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new MyModel();
